﻿Imports System.Windows.Forms

Public Class FIMServerSettings

    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
        If enableCredentialsCheckBox.Checked Then
            If Not String.IsNullOrEmpty(usernameTextBox.Text) AndAlso Not String.IsNullOrEmpty(passwordTextBox.Text) Then
                ' Generate a SecureString object and set the entered password as SecureString
                Dim securePassword As Security.SecureString = New Security.SecureString

                For i As Integer = 0 To passwordTextBox.TextLength - 1
                    securePassword.AppendChar(passwordTextBox.Text(i))
                Next

                AlternativePassword = securePassword
                AlternativeUsername = usernameTextBox.Text

                ' Save the entered values in the application settings file
                My.Settings.FIMServer = FIMServerTextBox.Text
                My.Settings.Username = usernameTextBox.Text
                My.Settings.Password = EncryptString(passwordTextBox.Text)
            Else
                ' Do nothing
            End If
        Else
            ' Dispose the alternative username and password
            AlternativeUsername = Nothing
            If Not AlternativePassword Is Nothing Then AlternativePassword.Dispose()

            My.Settings.Username = String.Empty
            My.Settings.Password = String.Empty
        End If

        Me.DialogResult = System.Windows.Forms.DialogResult.OK
        Me.Close()
    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub enableCredentialsCheckBox_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles enableCredentialsCheckBox.CheckedChanged
        If enableCredentialsCheckBox.Checked Then
            credentialsPanel.Enabled = True
        Else
            credentialsPanel.Enabled = False
        End If
    End Sub

    Private Sub FIMServerSettings_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        ' Load the values from the application settings file
        FIMServerTextBox.Text = My.Settings.FIMServer

        If Not (String.IsNullOrEmpty(My.Settings.Username) And String.IsNullOrEmpty(My.Settings.Password)) Then
            enableCredentialsCheckBox.Checked = True
            usernameTextBox.Text = My.Settings.Username
            passwordTextBox.Text = DecryptString(My.Settings.Password)
        End If
    End Sub
End Class
